import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class ThemeController extends GetxController {
  static ThemeController get to => Get.find();

  var themeMode = ThemeMode.system.obs;
  final _storage = GetStorage('theme_box');
  static const String _themeKey = 'theme_mode';

  @override
  void onInit() {
    super.onInit();
    _loadThemeFromStorage(); // 初始化主题
  }

  void switchTheme(ThemeMode mode) {
    themeMode.value = mode;
    Get.changeThemeMode(mode); // 更新全局主题
    _saveThemeToStorage(mode); // 保存到本地存储
  }

  void _loadThemeFromStorage() {
    final savedTheme = _storage.read<String>(_themeKey);
    if (savedTheme != null) {
      switch (savedTheme) {
        case 'light':
          themeMode.value = ThemeMode.light;
          break;
        case 'dark':
          themeMode.value = ThemeMode.dark;
          break;
        case 'system':
        default:
          themeMode.value = ThemeMode.system;
      }
    } else {
      themeMode.value = ThemeMode.system;
    }
  }

  void _saveThemeToStorage(ThemeMode mode) {
    String themeString;
    switch (mode) {
      case ThemeMode.light:
        themeString = 'light';
        break;
      case ThemeMode.dark:
        themeString = 'dark';
        break;
      case ThemeMode.system:
      default:
        themeString = 'system';
    }
    _storage.write(_themeKey, themeString);
  }
}
